KeyFactory = Packages.com.google.appengine.api.datastore.KeyFactory;
CalendarService = Packages.com.google.gdata.client.calendar.CalendarService;
gdata           = Packages.com.google.gdata.data;
AclEntry        = Packages.com.google.gdata.data.acl.AclEntry;
AclScope        = Packages.com.google.gdata.data.acl.AclScope;
CalendarAclRole = Packages.com.google.gdata.data.calendar.CalendarAclRole;
CalendarEventEntry =Packages.com.google.gdata.data.calendar.CalendarEventEntry;
DateTime         =  Packages.com.google.gdata.data.DateTime;
When             = Packages.com.google.gdata.data.extensions.When;
PlainTextConstruct = Packages.com.google.gdata.data.PlainTextConstruct;
EventWho         = Packages.com.google.gdata.data.calendar.EventWho;
Query            = Packages.com.google.gdata.client.Query;
CalendarEventFeed = Packages.com.google.gdata.data.calendar.CalendarEventFeed;
Reminder         = Packages.com.google.gdata.data.extensions.Reminder;
Method           = Packages.com.google.gdata.data.extensions.Reminder.Method;
Where            = Packages.com.google.gdata.data.extensions.Where;
ExtendedProperty = Packages.com.google.gdata.data.extensions.ExtendedProperty;
SimpleDateFormat = Packages.java.text.SimpleDateFormat;
ParseException   = Packages.java.text.ParseException;
Date             = Packages.java.util.Date;
CalendarEventFeed= Packages.com.google.gdata.data.calendar.CalendarEventFeed;
Link             = Packages.com.google.gdata.data.Link;
BatchUtils       = Packages.com.google.gdata.data.batch.BatchUtils;
BatchOperationType= Packages.com.google.gdata.data.batch.BatchOperationType;
CalendarQuery     = Packages.com.google.gdata.client.calendar.CalendarQuery;
ExtendedPropertyMatch=Packages.com.google.gdata.client.calendar.CalendarQuery.ExtendedPropertyMatch;

function main( ui ) {
//.getQueryParameters()
  var json = ui.getFirst("json");  
    if ( json == null ){
        var ex = "{ exception: { message: 'no param provided'} }";
        return ex;
  }
    var o = new JSONObject( json );
    var appointments= o.getJSONArray("records");
    var service = new CalendarService("demo-calendar-1");
    var username = "soulsoftware2010@gmail.com";
    var password = "2010soulsoftware";
    var batchRequest = new CalendarEventFeed();
    var test="";
  
  var i=0;
 
    var cal1 = java.util.Calendar.getInstance();
    
    for (;i<appointments.length();i++){
      try {
           var o=appointments.getJSONObject(i);
           
           var timeStartOffsetAppointment=o.get("TIMEZONE_START_TIMEOFFSETAPPOINTMENT_JSON_KEY");
           var timeStartOffsetEmployee=o.get("TIMEZONE_START_TIMEOFFSETEMPLOYEE_JSON_KEY");
           var timeEndOffsetAppointment=o.get("TIMEZONE_END_TIMEOFFSETAPPOINTMENT_JSON_KEY");
           var timeEndOffsetEmployee=o.get("TIMEZONE_END_TIMEOFFSETEMPLOYEE_JSON_KEY");
           var tzEmployee=o.get("TIMEZONE_EMPLOYEE_JSON_KEY");
           var tzAppointment=o.get("TIMEZONE_APPOINTMENT_JSON_KEY");

           cal1.setTimeInMillis(o.get("from"));
           var startDate = cal1.getTime();
           o.put("from",startDate);
      
           cal1.setTimeInMillis(o.get("to"));
           var endDate = cal1.getTime();
           o.put("to",endDate);
           
           var UID=o.get("UID");
           UID=UID.replace("\"","")
           o.put("UID", KeyFactory.stringToKey(UID))
           var event = new EventEntity();
              
           o.copyTo( event );
           
        
           BOLEntityManager.storeEvent( event );
        
           cal1 = java.util.Calendar.getInstance();
           cal1.setTimeInMillis(o.get("from2"));
           startDate = cal1.getTime();
           cal1.setTimeInMillis(o.get("to2"));
           endDate = cal1.getTime(); 
        
           /* GOOGLE CALENDAR*/

           var idCalendar=o.get("IDCALENDAR");
           var titleAppointment=o.get("TITLE");
           var contentAppointment=o.get("description");
           var emailEmployee=o.get("userId");
           var startAppointment=o.get("STARTDATE");
           var endAppointment=o.get("ENDDATE");
           var idCalendar=o.get("IDCALENDAR");
           var address=o.get("address");
           test=test + address + " " ;
          
           service.setUserCredentials(username, password);
           
           var postUrl =
               new java.net.URL("https://www.google.com/calendar/feeds/"+idCalendar+"/private/full");

           var myQuery = new CalendarQuery(postUrl);
           var match=new ExtendedPropertyMatch("IDEVENT_KEYEXT", UID);
           myQuery.setExtendedPropertyQuery(match);
        
           var resultFeed = service.query(myQuery,CalendarEventFeed);
           if (resultFeed.getEntries().size()>0)   {
              var myEntry = resultFeed.getEntries().get(0);
              
            contentAppointment=contentAppointment + " (EMPLOYEE GMT :" + (timeStartOffsetEmployee/60) + " " + tzEmployee +
            " - APPOINTMENT GMT :" +(timeStartOffsetAppointment/60)+ " " + tzAppointment +")";
             
              myEntry.setTitle(new PlainTextConstruct(titleAppointment));
              myEntry.setContent(new PlainTextConstruct(contentAppointment));

              //WHO
              var eventWho=new EventWho();
              eventWho.setEmail(emailEmployee);
              myEntry.getParticipants().clear()
              myEntry.addParticipant(eventWho);
              //WHEN
             
              var calendar = java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone(tzAppointment));
              var formatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
              var dateStart = formatter.parse(startAppointment);  
              var dateEnd = formatter.parse(endAppointment) ;

              calendar.setTime(startDate);
              var calculate=((-1)*timeStartOffsetEmployee *60*1000)-((-1)*timeStartOffsetAppointment*60*1000);
              var timeStartEmployee = new java.util.GregorianCalendar(java.util.TimeZone.getTimeZone(tzEmployee));
              timeStartEmployee.setTimeInMillis(calendar.getTimeInMillis() + calculate);
      
              calendar.setTime(endDate);
              calculate=((-1)*timeEndOffsetEmployee *60*1000)-((-1)*timeEndOffsetAppointment*60*1000);
              var timeEndEmployee = new java.util.GregorianCalendar(java.util.TimeZone.getTimeZone(tzEmployee));
              timeEndEmployee.setTimeInMillis(calendar.getTimeInMillis() + calculate);
          
              var startTime = new DateTime(timeStartEmployee.getTime(),java.util.TimeZone.getTimeZone(tzEmployee));
              var endTime = new DateTime(timeEndEmployee.getTime(),java.util.TimeZone.getTimeZone(tzEmployee));
             
             
              //var startTime = DateTime.parseDateTime(startAppointment);
              //var endTime = DateTime.parseDateTime(endAppointment);
              var eventTimes = new When();
              eventTimes.setStartTime(startTime);
              eventTimes.setEndTime(endTime);
              myEntry.getTimes().clear();
              myEntry.getTimes().add(eventTimes);
              //WHERE
              var where=new Where();
              where.setValueString(address);
              myEntry.getLocations().clear()
              myEntry.addLocation(where);
              //EXTENDEDPROPERTY
              var property = new ExtendedProperty();
              property.setName("IDEVENT_KEYEXT");
              property.setValue(UID);
              myEntry.getExtendedProperty().clear();
              myEntry.addExtendedProperty(property);
              //ADD REMIND
              var reminder = new Reminder();
              reminder.setMinutes(10);
              reminder.setMethod(Method.EMAIL);
              myEntry.getReminder().clear();
              myEntry.getReminder().add(reminder);

              BatchUtils.setBatchId(myEntry, java.lang.String.valueOf(i));
              BatchUtils.setBatchOperationType(myEntry, BatchOperationType.UPDATE);
              batchRequest.getEntries().add(myEntry);
             
              var batchUrl = new java.net.URL("https://www.google.com/calendar/feeds/"+idCalendar+"/private/full/batch");
              var batchResponse = service.batch(batchUrl, batchRequest);

            }
         }catch( e ) {
          var message ="Exception : " +titleAppointment;
          message=message + " Employee: " + emailEmployee;
          message=message + " Start date" + startAppointment;
          message=message + " End date" + endAppointment;
          
          throw (message);

        }     
   }
  return "{result:'OK'}";
}
